package utils

import (
	"unsafe"
	"bytes"
	"encoding/json"
	"path/filepath"
	"fmt"
	"runtime"
	"github.com/funlake/gopkg/utils/log"
)

func RoutineRecover(){
	if err := recover() ; err != nil{
		_, fn, line, _ := runtime.Caller(3)
		file := filepath.Base(fn)
		fd := fmt.Sprintf("[%s:%d]",file,line)
		log.Error("%s:%s",err,fd)
	}
}

func StrToByte(s string) []byte{
	x := (*[2]uintptr)(unsafe.Pointer(&s))
	h := [3]uintptr{x[0],x[1],x[1]}
	return *(*[]byte)(unsafe.Pointer(&h))
}

func ByteToStr(s []byte) string{
	return *(*string)(unsafe.Pointer(&s))
}
////涉及大量串连接采用，否则开销更大
//func StrConcat2(s ... string) string{
//	l := 0
//	for _,ss := range s{
//		l += len(ss)
//	}
//	bs := make([]byte, l)
//	bl := 0
//	for _,str := range s{
//		bl += copy(bs[bl:], str)
//	}
//	return ByteToStr(bs)
//}
func StrConcat(s ... string) string{
	var buffer bytes.Buffer
	for _,str := range s{
		buffer.WriteString(str)
	}
	return buffer.String()
}
//设置html过滤为false,否则默认的json marshal会过滤html字符,
//导致返回数据不是raw string
func JSONMarshal(t interface{}) ([]byte, error) {
	buffer := &bytes.Buffer{}
	encoder := json.NewEncoder(buffer)
	encoder.SetEscapeHTML(false)
	err := encoder.Encode(t)
	return buffer.Bytes(), err
}